package edu.visualization.homework.entity;

public class TreeUtils {

	private static double r = 0.4;

	public static void setTreeY(TreeNode root, double level) {
		if (root == null) {
			return;
		} else {
			root.setY(level);
			// set children level
			if (root.getChildren() != null) {
				for (TreeNode node : root.getChildren()) {
					setTreeY(node, level + 1.0);
				}
			}
		}
	}

	/**
	 * 设置每个节点对应的半轴的长度，根据点所在的层次（Y）值来计算
	 * 
	 * @param root
	 * @param step
	 */
	public static void setTreeP(TreeNode root, int roundr, int depth) {
		if (root == null) {
			return;
		} else {
			double y = root.getY();
			int nodedepth = root.getDepth();
			if (y + nodedepth == depth) {
				root.setP(roundr * root.getY());
			} else {
				root.setP(roundr * (depth - nodedepth ));
			}
			System.out.println("value: " + root.getValue()+", the p: "+root.getP());
			if (root.getChildren() != null) {
				for (TreeNode node : root.getChildren()) {
					setTreeP(node, roundr, depth);
				}
			}
		}
	}

	public static double postOrderTra(TreeNode root, double x) {
		if (root == null) {
			return x;
		} else {
			// child
			if (root.getChildren() != null) {
				for (TreeNode node : root.getChildren()) {
					x = postOrderTra(node, x);
				}
				root.setX(root.getParentX());
				return x;
			} else {
				root.setX(x);
				return x + r;
			}
		}
	}

	public static void getAngle(TreeNode root, double stepAngle, double beginAngle) {
		if (root != null) {
			int numOfLeaves = root.numOfLeaves();
			double angle = numOfLeaves * stepAngle;
			root.setBeginAngle(beginAngle);
			root.setEndAngle(beginAngle + angle);
			if (root.getChildren() != null) {
				int size = root.getChildren().size();
				for (int i = 0; i < size; i++) {
					TreeNode node = root.getChildren().get(i);
					numOfLeaves = node.numOfLeaves();
					angle = numOfLeaves * stepAngle;
					double endAngle = beginAngle + angle;
					getAngle(node, stepAngle, beginAngle);
					beginAngle = endAngle;
				}
			}
		}
	}

	/**
	 * 获得对应树的深度
	 * 
	 * @param root
	 * @return
	 */
	public static int getDepth(TreeNode root) {
		return root.getDepth();
	}

	public static int getNumOfLeaves(TreeNode root) {
		return root.numOfLeaves();
	}
}
